#include <iostream>
#include<string>
#include <vector>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
int cnt = 0;//票数
::sem_t sem;//信号量
::pthread_mutex_t lock;

void* consumer(void* arg)
{
    sem_wait(&sem);//P操作
    //cnt个消费者同时进入临界区内，再串行打印
    pthread_mutex_lock(&lock);//加锁
    cnt--;//消费一张票
    printf("%ld号消费者消费了一张票，剩余票数：%d\n", pthread_self(), cnt);
    pthread_mutex_unlock(&lock);//解锁
    sem_post(&sem);//V操作
    return nullptr;
}
int main(int argc, char* argv[])
{
    int num = 0;//消费者
    if(argc!= 3){
        std::cout << "Usage:./a.out cnt num" << std::endl;
        return 1;
    }
    cnt = std::stoi(argv[1]);//设置票数
    num = std::stoi(argv[2]);//设置消费者人数
    ::sem_init(&sem, 0, cnt);//初始化信号量
    printf("票数：%d 人数：%d\n", cnt, num);
    std::vector<::pthread_t> threads(num);
    pthread_mutex_init(&lock, nullptr);
    for(int i = 0; i < num; i++){
        ::pthread_create(&threads[i], nullptr, consumer, nullptr);
    }
    while(true){
        sleep(5);
        std::cout<<"主线程..."<<std::endl;
    }
    for(int i = 0; i < num; i++){
        ::pthread_join(threads[i], nullptr);
    }
    ::sem_destroy(&sem);

    return 0;
}